package com.detrum.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.media.MediaCodecInfo;
import android.media.MediaCodecList;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.text.TextUtils;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * Created by abc on 2017/11/27.
 */

public class NfsUtil {
    /**
     * 判断是否是文件夹
     * 通过文件属性mode，第一位为d则是文件夹
     */
    public static boolean isFolder(@Nullable String fileMode, String fileName) {
        if (TextUtils.equals("d", fileMode) &&fileName!=null&& !fileName.startsWith(".")){
            return true;
        }else return false;
    }

    /**
     * 判断是否是NFS文件
     * 暂时支持png，jpg，jpeg，mp4格式
     */
    public static boolean isNFSFile(@Nullable String fileName) {
        String filename = fileName.toLowerCase();
        if (filename.endsWith("png") || filename.endsWith(".jpg") || filename.endsWith(".mp4") || filename.endsWith("jpeg")
                || filename.endsWith("mov")) {
            return true;
        }else return false;
    }

    /**
     * 判断是否是视频文件
     * 暂时支持MP4格式
     */
    public static boolean isVideoFile(String fileName) {
        if (fileName.toLowerCase().endsWith(".mp4") || fileName.toLowerCase().endsWith("mov")) {
            return true;
        }else return false;
    }

    /**
     * 判断是否是图片文件
     * 暂时支持png，jpg，jpeg格式
     */
    public static boolean isImageFile(String fileName) {
        if (fileName.toLowerCase().endsWith("png") || fileName.toLowerCase().endsWith(".jpg") || fileName.toLowerCase().endsWith("jpeg")) {
            return true;
        }else return false;
    }

    /**
     * 获得SD卡缓存路径
     * @param uniqueName
     * @return
     */
    public static File getDiskCacheDir(Context context, String uniqueName) {
        String cachePath;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            cachePath = context.getExternalCacheDir().getPath();
        } else {
            cachePath = context.getCacheDir().getPath();
        }
        return new File(cachePath + File.separator + uniqueName);
    }

    /**
     * 获取应用版本号，用于更新缓存
     * @return
     */
    public static int getAppVersion(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 1;
    }

    /**
     * 对key进行MD5编码，使其符合缓存的命名规则
     * @param key
     * @return
     */
    public static String hashKeyForDisk(String key) {
        String cacheKey;
        try {
            final MessageDigest mDigest = MessageDigest.getInstance("MD5");
            mDigest.update(key.getBytes());
            cacheKey = bytesToHexString(mDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            cacheKey = String.valueOf(key.hashCode());
        }
        return cacheKey;
    }

    private static String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    /**
     * bitmap转成bytes
     * @param bitmap
     * @return
     */
    public static byte[] bitmap2Bytes(Bitmap bitmap) {
        if (bitmap == null)
        {
            return null;
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    /**
     * 获得下载的SD卡路径
     */
    public static File getDownloadDir(String fileDir) {
        String downloadDir;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            downloadDir = Environment.getExternalStorageDirectory().toString() + File.separator + DeviceFinal.FILE_DIR;
            return new File(downloadDir + File.separator + fileDir);
        }
        return null;
    }

    /**
     * nfs文件名转化，去除/
     */
    public static String splitName(String name) {
        String stringarray[] = name.split("/");
        return stringarray[stringarray.length - 1];
    }

    /**
     * 手机支持解码格式
     * @param mimeType
     * @return
     */
    public static boolean isSupportCodec(String mimeType) {
        int numCodecs = MediaCodecList.getCodecCount();
        for (int i = 0; i < numCodecs; i++) {
            MediaCodecInfo codecInfo = MediaCodecList.getCodecInfoAt(i);

            if (!codecInfo.isEncoder()) {
                continue;
            }

            String[] types = codecInfo.getSupportedTypes();
            for (int j = 0; j < types.length; j++) {
                if (types[j].equalsIgnoreCase(mimeType)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 将毫秒转成mm:ss的格式
     * @param time
     * @return
     */
    public static String formatTime(long time) {
        DateFormat formatter = new SimpleDateFormat("mm:ss");
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time);
        return formatter.format(calendar.getTime());
    }

}
